import { FC, useState, ChangeEvent } from "react";
import { useDispatch } from "react-redux";
import styles from "./Layers.module.scss";
import { Input, Space, Button, message } from "antd";
import { LockOutlined, EyeInvisibleOutlined } from "@ant-design/icons";
import useGetComponentInfo from "@/hooks/useGetComponentInfo";
import classnames from "classnames";
import {
  changeComponentHidden,
  changeComponentTitle,
  changeSelectedId,
  moveComponent,
  toggleComponentLock,
} from "@/store/componentsReducer";
import SortableContainer from "@/components/DragSortable/SortableContainer";
import SortableItem from "@/components/DragSortable/SortableItem";

const Layers: FC = () => {
  const { componentList, selectedId } = useGetComponentInfo();
  const dispatch = useDispatch();

  // 记录当前正在修改标题的组件
  const [changingTitleId, setChangingTitleId] = useState("");

  // 点击选中组件
  const handleTitleClick = (id: string) => {
    const curComp = componentList.find((c) => c.fe_id === id);
    if (curComp && curComp.isHidden) {
      message.info("不能选中隐藏组件");
      return;
    }
    if (id !== selectedId) {
      // 当前组件未被选中，执行选中
      dispatch(changeSelectedId(id));
      setChangingTitleId("");
      return;
    }
    // 点击修改标题
    setChangingTitleId(id);
  };

  const changeTitle = (e: ChangeEvent<HTMLInputElement>) => {
    const newTitle = e.target.value.trim();
    if (!newTitle) return;
    if (!selectedId) return;

    dispatch(
      changeComponentTitle({
        fe_id: selectedId,
        title: newTitle,
      })
    );
  };

  const changeHidden = (id: string, isHidden: boolean) => {
    dispatch(
      changeComponentHidden({
        fe_id: id,
        isHidden,
      })
    );
  };

  const changeLocked = (id: string) => {
    dispatch(toggleComponentLock({ fe_id: id }));
  };

  const componentListWithId = componentList.map((c) => ({ ...c, id: c.fe_id }));

  const handleDragEnd = (oldIndex: number, newIndex: number) => {
    dispatch(moveComponent({ oldIndex, newIndex }));
  };

  return (
    <SortableContainer items={componentListWithId} onDragEnd={handleDragEnd}>
      {componentList.map((c) => {
        const { fe_id, title, isHidden, isLocked } = c;

        const titleClassName = classnames({
          [styles.title]: true,
          [styles.selected]: fe_id === selectedId,
        });

        return (
          <SortableItem key={fe_id} id={fe_id}>
            <div className={styles.wrapper}>
              <div
                className={titleClassName}
                onClick={() => handleTitleClick(fe_id)}
              >
                {fe_id === changingTitleId && (
                  <Input
                    value={title}
                    onChange={changeTitle}
                    onPressEnter={() => setChangingTitleId("")}
                    onBlur={() => setChangingTitleId("")}
                  />
                )}
                {fe_id !== changingTitleId && title}
              </div>
              <div className={styles.handler}>
                <Space>
                  <Button
                    size="small"
                    shape="circle"
                    className={!isHidden ? styles.btn : ""}
                    icon={<EyeInvisibleOutlined />}
                    type={isHidden ? "primary" : "text"}
                    onClick={() => changeHidden(fe_id, !isHidden)}
                  />
                  <Button
                    size="small"
                    shape="circle"
                    className={!isLocked ? styles.btn : ""}
                    icon={<LockOutlined />}
                    type={isLocked ? "primary" : "text"}
                    onClick={() => changeLocked(fe_id)}
                  />
                </Space>
              </div>
            </div>
          </SortableItem>
        );
      })}
    </SortableContainer>
  );
};

export default Layers;
